package com.bifang.module.file.dao.service.impl;

import cn.hutool.core.convert.Convert;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CachePenetrationProtect;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.cache.jetcache.utils.JetCacheUtils;
import com.bifang.module.file.common.cache.FileCacheConst;
import com.bifang.module.file.common.vo.fileFieldParam.FileFieldParamVO;
import com.bifang.module.file.dao.mapper.FileFieldParamMapper;
import com.bifang.module.file.dao.model.FileFieldParam;
import com.bifang.module.file.dao.service.FileFieldParamService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
 * 文件元数据字段参数配置表服务实现类
 *
 * @author xyh
 * @since 2023-03-15
 */
@Service
public class FileFieldParamServiceImpl extends ServiceImpl<FileFieldParamMapper, FileFieldParam> implements FileFieldParamService {

    @Override
    @Cached(name= FileCacheConst.FILEFIELDKEY, key="#fieldKey", cacheType= CacheType.BOTH,expire = 2592000,localExpire=300)
    @CachePenetrationProtect
    public FileFieldParamVO getByKey(String fieldKey) {
        if (StringUtils.isBlank(fieldKey)){
            throw new AppException("字段编码不能为空");
        }
        QueryWrapper<FileFieldParam> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(FileFieldParam::getFieldKey,fieldKey);
        FileFieldParam fileFieldParam=this.getOne(queryWrapper,false);
        FileFieldParamVO retVO= Convert.convert(FileFieldParamVO.class,fileFieldParam);
        return retVO;
    }

    @Override
    public void clearKeyCache(String fieldKey) {
        if (StringUtils.isNotBlank(fieldKey)) {
            Cache<String, FileFieldParamVO> cache = JetCacheUtils.create(FileCacheConst.FILEFIELDKEY, CacheType.BOTH, Duration.ofSeconds(2592000), Duration.ofSeconds(300));
            if (cache != null) {
                cache.remove(fieldKey);
            }
        }
    }


}
